import urllib
from progressbar import *

class Downloader:
    
    def __init__(self):
        self.filename = ""
        self.headers = ""
        self.connection_established = False

    def download(self, url, location):
        
        filename_and_headers = urllib.urlretrieve(url, location, self.update_progress)
        self.progress.finish()
        self.filename = filename_and_headers[0]
        self.headers = filename_and_headers[1]

    def get_filename(self):
        return self.filename

    def get_headers(self):
        return self.headers

    def update_progress(self, blocks_completed, block_size, total_size):
        if self.connection_established == False:
            mb_size = total_size/1024.0/1024.0
            print "Total size of download is: " + str(round(mb_size, 2))  + " megabytes"

            widgets = [FileTransferSpeed(), '   ', Bar(), '   ', Percentage(), ' ', ETA()]
            self.progress = ProgressBar(widgets=widgets, maxval=total_size).start()
            self.connection_established = True
            return

        if (block_size * blocks_completed) <= total_size:
            self.progress.update((blocks_completed * block_size))
    
